package com.graduationproject.controller;
import ch.qos.logback.core.status.OnPrintStreamStatusListenerBase;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.graduationproject.common.R;
import com.graduationproject.entity.*;
import com.graduationproject.entity.dto.DishUserDTO;
import com.graduationproject.service.DishService;
import com.graduationproject.service.Impl.DishMakeServiceImpl;
import com.graduationproject.service.Impl.DishServiceImpl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author shkstart
 * @create 2023-12-04-14:28
 */
@RestController
@RequestMapping("api/dish")
public class DishController {
    @Autowired
    private DishServiceImpl dishService;

    /**
     * 根据id查找菜品
     *
     * @param id
     * @return
     */
    @GetMapping("/findDishById/{id}")
    public R<Dish> findDish(@PathVariable Integer id) {
        Dish dishById = dishService.findDishById(id);
        return R.success(dishById);
    }

    /**
     * 查询所有菜品及菜品的制作方法
     */
    @GetMapping("/findDishesAll/{num}")
    public R<List<Dish>> findDishesAll(@PathVariable Integer num) {
        List<Dish> dishesAll = dishService.findDishesAll();
        List<Dish> firstEight = dishesAll.subList(num, Math.min(num + 8, dishesAll.size()));
        return R.success(firstEight);
    }

    /**
     * 搜索功能
     *
     * @param input
     * @return
     */
    @GetMapping("/search")
    public R<List<Dish>> search(String input) {
        //根据关键字搜索菜品
        List<Dish> search = dishService.search(input);
        return R.success(search);
    }

    /**
     * 根据类型查找菜品
     *
     * @param type
     * @return
     */
    @GetMapping("/hotDishes/{type}")
    public R<List<Dish>> searchHotDishes(@PathVariable Integer type) {
        List<Dish> hotDishes = dishService.searchHotDishes(type);
        return R.success(hotDishes);
    }


    /**
     * 分页查询菜品数据以及菜品数据总量
     *
     * @param pageNow
     * @param pageSize
     * @return
     */
    @GetMapping("/findDishPage")
    public R findDishPage(String pageNow, String pageSize) {
        PageHelper.startPage(Integer.parseInt(pageNow), Integer.parseInt(pageSize)); // 开始分页
        PageResult<Dish> pageResult = dishService.findDishPage();
        return R.success(pageResult);
    }

    /**
     * 根据id删除菜品
     *
     * @param row
     * @return
     */
    @DeleteMapping("/deleteDish/{row}")
    public R<String> deleteDish(@PathVariable int row) {
        //删除菜品表
        dishService.deleteDish(row);

        //消除自增不连续
//        dishService.autoId();
        return R.success("删除成功");
    }

    /**
     * 根据id查找菜品及做法
     *
     * @param id
     * @return
     */
    @GetMapping("/findAllById/{id}")
    public R<Dish> findAllById(@PathVariable Integer id) {
        Dish dish = dishService.findAllById(id);
        return R.success(dish);
    }

    /**
     * 根据id修改菜品信息
     *
     * @param dish
     * @return
     */
//    @PutMapping("/dishPut")
//    public R<String> dishPut(@RequestBody Dish dish, HttpServletRequest request) {
//        Object imageName1 = request.getSession().getAttribute("imageName");
//        if (imageName1 != null) {
//            String imageName = imageName1.toString();
//            dish.setDishUrl(imageName);
//        } else {
//            dishService.dishPut(dish);
//            dishService.dishMakePut(dish.getMakes());
//            return R.success("修改成功");
//        }
//        dishService.dishPut(dish);
//        dishService.dishMakePut(dish.getDishMakes().get(0));
//        request.removeAttribute("imageName");
//        return R.success("修改成功");
//    }

    /**
     * 将图片下载到指定地址
     *
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public R<String> handleFileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return R.error("请选择上传文件");
        }
        try {
            byte[] bytes = file.getBytes();
            File saveFile = new File("C:\\Users\\此间最上乘\\Desktop\\毕设\\front\\src\\pages\\Main\\images\\" + file.getOriginalFilename());
            FileOutputStream fileOutputStream = new FileOutputStream(saveFile);
//            HttpSession session = request.getSession();
//            session.setAttribute("imageName", file.getOriginalFilename());
            fileOutputStream.write(bytes);
            fileOutputStream.close();
            return R.success("文件上传成功");
        } catch (IOException e) {
            return R.error("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 新增菜品
     *
     * @param dish
     * @param request
     * @return
     */
//    @PostMapping("/addDishAndMake")
//    public R<String> addDishAndMake(@RequestBody Dish dish, HttpServletRequest request) {
//        Object imageName1 = request.getSession().getAttribute("imageName");
//        if (imageName1 != null) {
//            String imageName = imageName1.toString();
//            dish.setDishUrl(imageName);
//        } else {
//            dish.setDishUrl("未上传照片");
//            dishService.addDishAndMake(dish);
//            dishService.addDishMake(dish.getDishMakes().get(0));
//            return R.success("添加成功");
//        }
//        dishService.addDishAndMake(dish);
//        DishMake dishMake = dish.getDishMakes().get(0);
//        dishMake.setName(dish.getDishName());
//        dishService.addDishMake(dishMake);
//        request.removeAttribute("imageName");
//        return R.success("添加成功");
//
//    }

    /**
     * 菜品匹配
     *
     * @param number
     * @param sum
     * @return
     */
    @GetMapping("/matchDish")
    public R<List<Dish>> matchDish(String number, String sum) {
        ArrayList<Dish> dishes = dishService.matchDish(number, sum);
        if (dishes.size() < Integer.parseInt(number)) {
            return R.error("菜品资料不足，未匹配到数据");
        }
        return R.success(dishes);
    }

    /**
     * 将菜单中菜品记录
     *
     * @param dishUserDTO
     * @return
     */
    @PostMapping("/addDishRecord")
    public R<String> addDishRecord(@RequestBody DishUserDTO dishUserDTO) {
        //将json字符串转换为对象数组
        Gson gson = new Gson();
        Type listType = new TypeToken<List<Dish>>() {
        }.getType();
        List<Dish> dishes = gson.fromJson(dishUserDTO.getDishInfo(), listType);
        String username = dishUserDTO.getUsername();
        dishService.addDishRecord(dishes, username);
        return R.success("记录成功");
    }

    /**
     * 获取菜品记录表里的数据
     *
     * @param username
     * @return
     */
    @GetMapping("/getDishRecord/{username}")
    public R<List<DishRecord>> getDishRecord(@PathVariable String username) {
        List<DishRecord> dishRecord = dishService.getDishRecord(username);
        return R.success(dishRecord);
    }

    /**
     * 根据时间查找菜品
     *
     * @param startTime
     * @param endTime
     * @param username
     * @return
     */
    @GetMapping("/findByTime")
    public R<List<DishRecord>> findByTime(String startTime, String endTime, String username) {
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            //对时间格式进行加工，以便能够在数据库里找到数据
            Date startTimee = inputFormat.parse(startTime);
            Date endTimee = inputFormat.parse(endTime);
            //startTimee加8小时
            Calendar cal = Calendar.getInstance();
            cal.setTime(startTimee);
            cal.add(Calendar.HOUR_OF_DAY, 8); // 加上八个小时
            Date startTimeee = cal.getTime();
            String startTimeeee = outputFormat.format(startTimeee);
            //startTimee加8小时
            cal.setTime(endTimee);
            cal.add(Calendar.HOUR_OF_DAY, 8); // 加上八个小时
            Date endTimeee = cal.getTime();
            String endTimeeee = outputFormat.format(endTimeee);
            //查找数据
            List<DishRecord> byTime = dishService.findByTime(startTimeeee, endTimeeee, username);
            return R.success(byTime);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 根据时间查找菜品的热量
     *
     * @param startTime
     * @param endTime
     * @param username
     * @return
     */
    @GetMapping("/findDishByTime")
    public R<DishFindByTime> findDishByTime(String startTime, String endTime, String username, String energy) {
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
        SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date1 = null;
        Date date2 = null;
        try {
            date1 = outputFormat.parse(startTime);
            date2 = outputFormat.parse(endTime);
            // 计算两个日期之间的毫秒数差
            long timeDiff = date2.getTime() - date1.getTime();
            // 将毫秒数差转换为天数差
            int dayDiff = (int) timeDiff / (1000 * 60 * 60 * 24);
            //startTime加8小时
            Calendar cal = Calendar.getInstance();
            cal.setTime(date1);
            cal.add(Calendar.HOUR_OF_DAY, 8); // 加上八个小时
            cal.add(Calendar.DAY_OF_MONTH, 1);// 加上一天
            Date startTimeee = cal.getTime();
            String startTimeeee = outputFormat.format(startTimeee);
            cal.add(Calendar.HOUR_OF_DAY, 8); // 加上八个小时
            cal.add(Calendar.DAY_OF_MONTH, 1);// 加上一天
            Date time = cal.getTime();
            String format = outputFormat.format(time);
            int[] ints = new int[dayDiff];
            int[] row = new int[dayDiff];
            //循环获取每一天热量的总和
            for (int i = 0; i < dayDiff; i++) {
                int heatByTime = dishService.findDishByTime(startTimeeee, format, username);
                ints[i] = heatByTime;
                cal.setTime(outputFormat.parse(startTimeeee));
                cal.add(Calendar.DAY_OF_MONTH, 1);
                startTimeeee = outputFormat.format(cal.getTime());
                cal.setTime(outputFormat.parse(format));
                cal.add(Calendar.DAY_OF_MONTH, 1);
                format = outputFormat.format(cal.getTime());
            }
            DishFindByTime dishFindByTime = new DishFindByTime();
            dishFindByTime.setNumber(ints);
            for (int i = 1; i <= dayDiff; i++) {
                row[i - 1] = i;
            }
            dishFindByTime.setSum(row);
            int[] msgs = new int[dayDiff];
            Double.parseDouble(energy);
            int energys = (int) Double.parseDouble(energy);
            for (int i = 1; i <= dayDiff; i++) {
                msgs[i - 1] = energys;
            }
            dishFindByTime.setMag(msgs);
            return R.success(dishFindByTime);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 获取轮播图数据
     * @return
     */
    @GetMapping("/getCarouselChart")
    public R<List<Dish>> getCarouselChart() {
        List<Dish> carouselChart = dishService.getCarouselChart();
        return R.success(carouselChart);
    }
}
